﻿using HowToEatMeat.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HowToEatMeat
{
    public partial class MainForm : Sunny.UI.UIForm
    {
        private readonly BindingList<Record> records = new BindingList<Record>();
        private readonly Color defaultRectColor = Color.FromArgb(80, 160, 255);
        private double totalOfDay = 0;
        private double totalOfAll = 0;
        private double mouthIn = 0;
        private double mouthOut = 0;
        private bool showDelete = false;
        private string dayString;
        private string mouthInString;
        private string mouthOutString;
        private List<double> seriesInList = new List<double>();
        private List<double> seriesOutList = new List<double>();
        private Task SeriesLoadingTask;
        private List<string> xAxisList = new List<string>();
        private Mutex mutex;

        public MainForm()
        {
            InitializeComponent();
            uiDataGridView1.AutoGenerateColumns = false;
            uiDataGridView1.DataSource = records;
        }

        private void MainLoad(object sender, EventArgs e)
        {
            if (Mutex.TryOpenExisting("HTEM By szcgy", out mutex))
            {
                Sunny.UI.UIMessageDialog.ShowInfoDialog(this, "程序已打开请勿重复开启");
                mutex = null;
                this.Close();
            }
            else
            {
                mutex = new Mutex(true, "HTEM By szcgy");
            }
            string passWord = string.Empty;
            FileInfo dbFile = new FileInfo(".\\Data.db");
            if (!Sunny.UI.UIInputDialog.InputPasswordDialog(this, ref passWord, desc: dbFile.Exists ? "请输入密码：" : "请设置密码："))
            {
                this.Close();
                return;
            }
            if (!DataBase.SetPassWord(passWord, out var msg))
            {
                if (msg == "Invalid password")
                    msg = "密码错误";
                Sunny.UI.UIMessageDialog.ShowErrorDialog(this, msg);
                this.Close();
                return;
            }

            uiDatePicker1.Value = DateTime.Today.Date;
            totalOfAll = DataBase.SumAllReacord();
            uiLabel4.Text = totalOfAll.ToString("#.##");
            RecordShow(uiDatePicker1.Value);
            Task.Run(ShowCaculation);
        }

        private void AddRecord(object sender, EventArgs e)
        {
            if (uiTextBox1.DoubleValue <= 0)
            {
                uiTextBox1.RectColor = Color.Red;
                return;
            }
            var value = uiSwitch1.Active ? uiTextBox1.DoubleValue : -uiTextBox1.DoubleValue;
            uiTextBox1.RectColor = defaultRectColor;
            var newOne = DataBase.AddOne(value, uiTextBox2.Text, uiDatePicker1.Value.Date);
            if (newOne != null)
            {
                if (uiSwitch1.Active)
                    mouthIn += uiTextBox1.DoubleValue;
                else
                    mouthOut += uiTextBox1.DoubleValue;
                records.Add(newOne);
                uiTextBox2.Text = string.Empty;
                uiTextBox1.DoubleValue = 0d;
                uiTextBox1.Focus();
                uiTextBox1.SelectAll();
                totalOfDay += value;
                uiLabel2.Text = totalOfDay.ToString("#.##");
                totalOfAll += value;
                uiLabel4.Text = totalOfAll.ToString("#.##");
                DataBase.SetCaculation(dayString, totalOfDay);
                DataBase.SetCaculation("TotalOfAll", totalOfAll);
                DataBase.SetCaculation(mouthInString, mouthIn);
                DataBase.SetCaculation(mouthOutString, mouthOut);
            }
        }

        private void DateChange(object sender, DateTime value)
        {
            RecordShow(value);
        }

        private void ValueEnter(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
                uiTextBox2.Focus();
        }

        private void RecordEnter(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
                this.AddRecord(null, null);
        }

        private void RecordShow(DateTime date)
        {
            records.Clear();
            var record = DataBase.GetRecords(date, out totalOfDay, out dayString);
            uiLabel2.Text = totalOfDay.ToString();
            if (record != null && record.Count > 0)
            {
                foreach (var item in record)
                {
                    records.Add(item);
                }
            }
            string mouthInStringTemp = mouthInString;
            mouthIn = DataBase.GetMonthsIn(date, out mouthInString);
            mouthOut = DataBase.GetMonthsOut(date, out mouthOutString);
            if (mouthInStringTemp != mouthInString)
                SeriesLoadingTask = Task.Run(LoadSeries);
        }

        private void EditModeActive(object sender, EventArgs e)
        {
            showDelete = !showDelete;
            ColumnDeleteCheckBox.Visible = showDelete;
            uiLinkLabel2.Visible = showDelete;
            uiLinkLabel1.Text = showDelete ? "取消" : "编辑";
        }

        private void DeleteRow(object sender, EventArgs e)
        {
            List<int> removeList = new List<int>();
            foreach (DataGridViewRow row in uiDataGridView1.Rows)
            {
                if (row.Cells[0] is DataGridViewCheckBoxCell checkBoxCell)
                {
                    if ((checkBoxCell.Value as bool?) ?? false)
                    {
                        if (DataBase.ReomveOne(records[row.Index]._id))
                        {
                            removeList.Add(row.Index);
                        }
                    }
                }
            }
            foreach (var item in removeList.OrderByDescending(m => m))
            {
                totalOfAll -= records[item].Value;
                totalOfDay -= records[item].Value;
                if (records[item].Value > 0)
                    mouthIn -= records[item].Value;
                else
                    mouthOut += records[item].Value;
                records.RemoveAt(item);
            }
            uiLabel2.Text = totalOfDay.ToString("#.##");
            uiLabel4.Text = totalOfAll.ToString("#.##");
            DataBase.SetCaculation(dayString, totalOfDay);
            DataBase.SetCaculation("TotalOfAll", totalOfAll);
            DataBase.SetCaculation(mouthInString, mouthIn);
            DataBase.SetCaculation(mouthOutString, mouthOut);
            EditModeActive(null, null);
        }

        private void ShowCaculation()
        {
            Sunny.UI.UIBarOption option = new Sunny.UI.UIBarOption();
            option.Title = new Sunny.UI.UITitle();
            option.Title.Text = $"总计余额：{totalOfAll:#.##}";
            option.Title.Top = Sunny.UI.UITopAlignment.Bottom;

            //设置Legend
            option.Legend = new Sunny.UI.UILegend();
            option.Legend.Orient = Sunny.UI.UIOrient.Horizontal;
            option.Legend.Top = Sunny.UI.UITopAlignment.Bottom;
            option.Legend.Left = Sunny.UI.UILeftAlignment.Left;
            option.Legend.AddData("收入");
            option.Legend.AddData("支出");
            option.Legend.Colors.Add(Color.LightGreen);
            option.Legend.Colors.Add(Color.LightCoral);

            option.ToolTip = new Sunny.UI.UIBarToolTip();
            option.ToolTip.ValueFormat = "#.##";

            if (SeriesLoadingTask != null && SeriesLoadingTask.Status == TaskStatus.Running)
            {
                SeriesLoadingTask.Wait();
            }
            var seriesIn = new Sunny.UI.UIBarSeries() { Name = "收入" };
            var seriesOut = new Sunny.UI.UIBarSeries() { Name = "支出" };
            for (int i = 0; i < 11; i++)
            {
                seriesIn.AddData(seriesInList[i], Color.LightGreen);
                seriesOut.AddData(seriesOutList[i], Color.LightCoral);
            }
            seriesIn.AddData(mouthIn, Color.LightGreen);
            seriesOut.AddData(mouthOut, Color.LightCoral);
            option.Series.Add(seriesIn);
            option.Series.Add(seriesOut);
            option.XAxis.Data.AddRange(xAxisList);
            option.Grid.Top = 20;
            option.Grid.Left = 50;
            option.Grid.Right = 20;

            uiBarChart1.SetOption(option);
        }

        private void uiTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uiTabControl1.SelectedIndex == 1)
            {
                ShowCaculation();
            }
        }

        private void LoadSeries()
        {
            seriesInList.Clear();
            seriesOutList.Clear();
            xAxisList.Clear();
            for (int i = -11; i < 0; i++)
            {
                var time = uiDatePicker1.Value.AddMonths(i);
                seriesInList.Add(DataBase.GetMonthsIn(time, out _));
                seriesOutList.Add(DataBase.GetMonthsOut(time, out _));
                xAxisList.Add($"{time.Month:D02}月");
            }
            xAxisList.Add($"{uiDatePicker1.Value.Month:D02}月");
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            mutex?.ReleaseMutex();
        }
    }
}
